﻿using DataPersistence;
using Newtonsoft.Json.Linq;
using NLog;
using QueryDataLogic;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace PersistenceDataLogic
{
    
    public class OperationMeal
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        PersistenceData pd = new PersistenceData();
        QueryData qd = new QueryData();
        BasicInfo bi = new BasicInfo();
        SystemSetting ss = new SystemSetting();

        /// <summary>
        /// 返回消息处理
        /// </summary>
        /// <param name="resultLine">保存数据库返回的受影响行数</param>
        /// <param name="state">客户端请求的 服务器处理状态 Add或Del</param>
        /// <param name="Date">报餐日期</param>
        /// <param name="UserID">用户ID</param>
        /// <param name="MealID">餐点ID</param>
        /// <param name="name">餐点名称</param>
        /// <param name="dbName">数据库名称</param>
        /// <returns></returns>
        private string ResultHandle(int resultLine, string state, string Date,int UserID,int MealID, string name, string dbName)
        {
            StringBuilder sbMessage = new StringBuilder();
            JArray jaIsReportMeal = new JArray();
            //返回消息处理
            if (resultLine > 0)
            {
                if (state == "Add")
                {
                    if (name != "")
                    {
                        sbMessage.Append("[" + DateTime.Now.ToShortTimeString() + "]：" + Date + " 的“" + name + "”报餐成功\n");
                    }
                }
                else if (state == "Del")
                {
                    if (name != "")
                    {
                        sbMessage.Append("[" + DateTime.Now.ToShortTimeString() + "]：" + Date + " 的“" + name + "”撤餐成功\n");
                    }
                }
            }
            else
            {
                jaIsReportMeal = IsMealReport(UserID, Date, MealID, dbName);
                if (jaIsReportMeal.Count > 0)
                {
                    sbMessage.Append("[" + DateTime.Now.ToShortTimeString() + "]：" + Date + " 的“" + name + "”已在“" + (string)(jaIsReportMeal[0]["hallName"]) + "”报餐\n");
                }
                //if (state == "Add")
                //{
                //    if (name != "")
                //    {
                //        sbMessage.Append("[" + DateTime.Now.ToShortTimeString() + "]：" + Date + " 的“" + name + "”已报餐\n");
                //    }
                //}
                //else if (state == "Del")
                //{
                //    if (name != "")
                //    {
                //        sbMessage.Append("[" + DateTime.Now.ToShortTimeString() + "]：" + Date + " 的“" + name + "”未报餐\n");
                //    }
                //}
            }

            return sbMessage.ToString();
        }
        
        /// <summary>
        /// 判断是否存在报餐信息
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="Date"></param>
        /// <param name="hallID"></param>
        /// <param name="mealID"></param>
        /// <returns></returns>
        private JArray IsMealReport(int UserID,string Date,int mealID, string dbName)
        {
            JArray ja = new JArray();
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "SELECT u.mobile,u.number,u.name,dh.hallNumber,dh.hallName,m.mealNumber,m.mealName,rm.[date],rm.dayIndex, \r\n" +
                                    "datediff(s, CONVERT(varchar(100), getdate(), 23), rm.[date]) / 60 / 60 / 24 AS newIndex, \r\n" +
                                    "rm.[month], rm.qty, m.price AS amount, rm.creationDate FROM ReportMeals rm \r\n" +
                                    "INNER JOIN MealUser u ON u.UserID = rm.UserID \r\n" +
                                    "INNER JOIN DiningHall dh ON dh.HallID = rm.HallID \r\n" +
                                    "INNER JOIN MealTime m ON m.MealID = rm.MealID \r\n" +
                                    "WHERE u.UserID = @UserID AND rm.[date] = @Date AND rm.MealID = @MealID "
                };

                comm.Parameters.AddWithValue("@UserID", UserID);
                comm.Parameters.AddWithValue("@Date", Date);
                comm.Parameters.AddWithValue("@MealID", mealID);

                ja = qd.GetData(comm, dbName);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
            }
            return ja;
        }

        private JObject ExeMeal(JArray jaParam, int districtID, string dbName)
        {
            JObject joResult = new JObject();
            try
            {
                JObject joParamItem = new JObject();
                JArray jaIsReportMeal = new JArray();
                int resultLine = 0;
                int AllResultLing = 0;
                //返回的消息
                StringBuilder sbMessage = new StringBuilder();

                int UserID = 0;
                int HallID = 0;
                string Date = "";
                int MealID = 0;
                int dayIndex = 0;
                int month = 0;
                int qty = 0;
                string state = "";//客户端通知服务端是 新增或者删除
                string name = "";//餐点名称 消息提示用

                for (int paramIndex = 0; paramIndex < jaParam.Count; paramIndex++)
                {
                    joParamItem = (JObject)jaParam[paramIndex];
                    UserID = (int)joParamItem["userID"];
                    HallID = (int)joParamItem["hallID"];
                    Date = (string)joParamItem["date"];
                    MealID = (int)joParamItem["mealID"];
                    dayIndex = (int)joParamItem["dayIndex"];
                    month = (int)joParamItem["month"];
                    qty = (int)joParamItem["qty"];
                    state = (string)joParamItem["state"];
                    name = (string)joParamItem["name"];

                    SqlCommand comm = new SqlCommand();
                    if (state == "Add")
                    {
                        comm.CommandText = "INSERT INTO ReportMeals(UserID,HallID,Date,MealID,dayIndex,month,qty,districtID) VALUES(@UserID,@HallID,@Date,@MealID,@dayIndex,@month,@qty,@districtID)";
                    }
                    else if (state == "Del")
                    {
                        comm.CommandText = "DELETE FROM ReportMeals WHERE UserID = @UserID AND HallID = @HallID AND MealID = @MealID AND Date = @Date ";
                    }

                    comm.Parameters.AddWithValue("@UserID", UserID);
                    comm.Parameters.AddWithValue("@HallID", HallID);
                    comm.Parameters.AddWithValue("@Date", Date);
                    comm.Parameters.AddWithValue("@MealID", MealID);
                    comm.Parameters.AddWithValue("@dayIndex", dayIndex);
                    comm.Parameters.AddWithValue("@month", month);
                    comm.Parameters.AddWithValue("@qty", qty);
                    comm.Parameters.AddWithValue("@districtID", districtID);

                    jaIsReportMeal = IsMealReport(UserID, Date, MealID, dbName);
                    if (jaIsReportMeal.Count > 0 && state == "Add")
                    {
                        resultLine = 0;
                        AllResultLing += resultLine;
                    }
                    else
                    {
                        resultLine = pd.ExeSqlCode(comm, dbName);
                        AllResultLing += resultLine;
                    }

                    //返回消息处理
                    sbMessage.Append(ResultHandle(resultLine, state, Date, UserID, MealID, name, dbName));
                }

                if (sbMessage.ToString() != "")
                {
                    joResult["message"] = sbMessage.ToString();
                }
                else
                {
                    joResult["message"] = "[" + DateTime.Now.ToShortTimeString() + "]：撤销日期为“" + Date + "”的所有报餐。\n";
                }
                joResult["data"] = AllResultLing;
                joResult["state"] = true;

                Console.Write("\n数据库：" + dbName + " 区域ID：" + districtID + "用户ID：" + UserID + "\n消息：\n" + sbMessage.ToString());
                //记录客户报餐的消息
                logger.Info("\n数据库：" + dbName + " 区域ID：" + districtID + "用户ID：" + UserID + "\n消息：\n" + sbMessage.ToString());
            }
            catch(Exception ex)
            {
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }
            return joResult;
        }

        /// <summary>
        /// 判断是否点过菜了
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="date"></param>
        /// <param name="districtID"></param>
        /// <param name="dbName"></param>
        /// <returns></returns>
        private bool IsUserDishes(int userID, string date, int districtID, string dbName)
        {
            JArray ja = new JArray();
            try
            {
                SqlCommand comm = new SqlCommand()
                {
                    CommandText = "select id,userID,dishesID,[date],remark,districtID,hallID from UserDishes " +
                    "where districtID = @districtID and [date] = @date and userID = @userID "
                };

                comm.Parameters.AddWithValue("@userID", userID);
                comm.Parameters.AddWithValue("@date", date);
                comm.Parameters.AddWithValue("@districtID", districtID);

                ja = qd.GetData(comm, dbName);

                if (ja.Count > 0)
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Console.Write(ex);
            }
            return false;
        }

        /// <summary>
        /// 新增报餐
        /// </summary>
        /// <returns></returns>
        public JObject AddMeal(JObject joParam)
        {
            JObject joResult = new JObject();
            try
            {
                JArray jaParam = (JArray)joParam["meal"];
                //logger.Info(jaParam);
                
                //因为区域ID在JSON数组中的每项都相同所以提取第一项即可，来获取数据库名称 提高性能
                JObject joPItem = (JObject)jaParam[0];
                int districtID  = (int)joPItem["districtID"];
                int userID = (int)joPItem["userID"];
                string date = (string)joPItem["date"];
                string dbName = bi.GetDBName(districtID);
                
                JObject joSetting = ss.GetSystemSetting(districtID);
                bool ConstraintDishes = (bool)joSetting["ConstraintDishes"];

                //强制点菜时，控制报餐时必须先点菜
                if (ConstraintDishes)
                {
                    //判断用户是否点过菜了，点过菜则执行报餐，未点过菜则提示先点菜
                    if (IsUserDishes(userID, date, districtID, dbName))
                    {
                        joResult = ExeMeal(jaParam, districtID, dbName);
                    }
                    else
                    {
                        joResult["message"] = "[" + DateTime.Now.ToShortTimeString() + "]：日期:“" + date + "”未点菜，请先点菜。\n";
                        joResult["data"] = 0;
                        joResult["state"] = false;
                    }
                }
                else
                {
                    joResult = ExeMeal(jaParam, districtID, dbName);
                }
                
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }
            return joResult;
        }

        /// <summary>
        /// 新增 家属报餐
        /// </summary>
        /// <returns></returns>
        public JObject AddFamilyIncrementalMeal(JObject joParam)
        {
            JObject joResult = new JObject();

            try
            {
                int resultLine = 0;

                int UserID = (int)joParam["userID"];
                int HallID = (int)joParam["hallID"];
                string Date = (string)joParam["date"];
                int MealID = (int)joParam["mealID"];
                int qty = (int)joParam["qty"];
                string state = (string)joParam["state"];
                int type = (int)joParam["type"];
                int districtID = (int)joParam["districtID"];
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand();
                if (state == "add")
                {
                    comm.CommandText = "INSERT INTO IncrementalMeal(type,UserID,HallID,Date,MealID,qty,districtID,creatorId) VALUES(@type,@UserID,@HallID,@Date,@MealID,@qty,@districtID,@UserID)";
                }
                else if (state == "modify")
                {
                    comm.CommandText = "UPDATE IncrementalMeal SET HallID = @HallID,MealID = @MealID, Date = @Date,qty = @qty WHERE type = @type AND UserID = @UserID AND HallID = @HallID AND MealID = @MealID AND Date = @Date ";
                }
                else if (state == "del")
                {
                    comm.CommandText = "DELETE FROM IncrementalMeal WHERE type = @type AND UserID = @UserID AND HallID = @HallID AND MealID = @MealID AND Date = @Date ";
                }

                comm.Parameters.AddWithValue("@type", type);
                comm.Parameters.AddWithValue("@UserID", UserID);
                comm.Parameters.AddWithValue("@HallID", HallID);
                comm.Parameters.AddWithValue("@Date", Date);
                comm.Parameters.AddWithValue("@MealID", MealID);
                comm.Parameters.AddWithValue("@qty", qty);
                comm.Parameters.AddWithValue("@districtID", districtID);

                resultLine = pd.ExeSqlCode(comm, dbName);

                if (state == "add" && resultLine > 0)
                {
                    joResult["message"] = "添加家属报餐 " + Date + " 成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else if (state == "add" && resultLine <= 0)
                {
                    joResult["message"] = "添加家属报餐 " + Date + " 失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }
                else if (state == "modify" && resultLine > 0)
                {
                    joResult["message"] = "修改家属报餐 " + Date + " 成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else if (state == "modify" && resultLine <= 0)
                {
                    joResult["message"] = "修改家属报餐 " + Date + " 失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }
                else if (state == "del" && resultLine > 0)
                {
                    joResult["message"] = "删除家属报餐 " + Date + " 成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else if (state == "del" && resultLine <= 0)
                {
                    joResult["message"] = "删除家属报餐 " + Date + " 失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }
            return joResult;
        }

        /// <summary>
        /// 新增 临时报餐
        /// </summary>
        /// <returns></returns>
        public JObject AddInterimIncrementalMeal(JObject joParam)
        {
            JObject joResult = new JObject();

            try
            {
                int resultLine = 0;

                int UserID = (int)joParam["userID"];
                int HallID = (int)joParam["hallID"];
                string Date = (string)joParam["date"];
                int MealID = (int)joParam["mealID"];
                int qty = (int)joParam["qty"];
                string state = (string)joParam["state"];
                int type = (int)joParam["type"];
                int districtID = (int)joParam["districtID"];
                string Remark = (string)joParam["remark"];
                //string CreatorId = (string)joParam["creatorId"];
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand();
                if (state == "add")
                {
                    comm.CommandText = "INSERT INTO IncrementalMeal(type,UserID,HallID,Date,MealID,qty,districtID,Remark,creatorId) VALUES(@type,@UserID,@HallID,@Date,@MealID,@qty,@districtID,@Remark,@UserID)";
                }
                else if (state == "modify")
                {
                    comm.CommandText = "UPDATE IncrementalMeal SET HallID = @HallID,MealID = @MealID, Date = @Date,qty = @qty,Remark=@Remark WHERE type = @type AND UserID = @UserID AND HallID = @HallID AND MealID = @MealID AND Date = @Date ";
                }
                else if (state == "del")
                {
                    comm.CommandText = "DELETE FROM IncrementalMeal WHERE type = @type AND UserID = @UserID AND HallID = @HallID AND MealID = @MealID AND Date = @Date ";
                }

                comm.Parameters.AddWithValue("@type", type);
                comm.Parameters.AddWithValue("@UserID", UserID);
                comm.Parameters.AddWithValue("@HallID", HallID);
                comm.Parameters.AddWithValue("@Date", Date);
                comm.Parameters.AddWithValue("@MealID", MealID);
                comm.Parameters.AddWithValue("@qty", qty);
                comm.Parameters.AddWithValue("@districtID", districtID);
                comm.Parameters.AddWithValue("@Remark", Remark);
                //comm.Parameters.AddWithValue("@creatorId", CreatorId);

                resultLine = pd.ExeSqlCode(comm, dbName);

                if (state == "add" && resultLine > 0)
                {
                    joResult["message"] = "添加临时报餐 " + Date + " 成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else if (state == "add" && resultLine <= 0)
                {
                    joResult["message"] = "添加临时报餐 " + Date + " 失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }
                else if (state == "modify" && resultLine > 0)
                {
                    joResult["message"] = "修改临时报餐 " + Date + " 成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else if (state == "modify" && resultLine <= 0)
                {
                    joResult["message"] = "修改临时报餐 " + Date + " 失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }
                else if (state == "del" && resultLine > 0)
                {
                    joResult["message"] = "删除临时报餐 " + Date + " 成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else if (state == "del" && resultLine <= 0)
                {
                    joResult["message"] = "删除临时报餐 " + Date + " 失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }

            }
            catch (Exception ex)
            {
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }

            return joResult;
        }

        /// <summary>
        /// 操作 加班餐
        /// </summary>
        /// <returns></returns>
        public JObject AddWorkOvertimeMeal(JObject joParam)
        {
            JObject joResult = new JObject();

            try
            {
                int resultLine = 0;

                int UserID = (int)joParam["userID"];
                int HallID = (int)joParam["hallID"];
                string Date = (string)joParam["date"];
                int MealID = (int)joParam["mealID"];//固定晚餐 客户端传入
                int qty = (int)joParam["qty"];
                string state = (string)joParam["state"];
                int districtID = (int)joParam["districtID"];
                string Remark = (string)joParam["remark"];
                string dbName = bi.GetDBName(districtID);

                SqlCommand comm = new SqlCommand();
                if (state == "add")
                {
                    comm.CommandText = "INSERT INTO IncrementalMeal(type,UserID,HallID,Date,MealID,qty,districtID,Remark, isAudit, creatorId) VALUES(3,@UserID,@HallID,@Date,@MealID,@qty,@districtID,@Remark, 0, @UserID)";
                }
                else if (state == "modify")
                {
                    //客户端判断已审核无法修改 移除对应的按钮
                    comm.CommandText = "UPDATE IncrementalMeal SET HallID = @HallID,MealID = @MealID, Date = @Date,qty = @qty,Remark=@Remark WHERE type = 3 AND UserID = @UserID AND HallID = @HallID AND MealID = @MealID AND Date = @Date ";
                }
                else if (state == "del")
                {
                    //客户端判断已审核无法删除 移除对应的按钮
                    comm.CommandText = "DELETE FROM IncrementalMeal WHERE type = 3 AND UserID = @UserID AND HallID = @HallID AND MealID = @MealID AND Date = @Date ";
                }
                
                comm.Parameters.AddWithValue("@UserID", UserID);
                comm.Parameters.AddWithValue("@HallID", HallID);
                comm.Parameters.AddWithValue("@Date", Date);
                comm.Parameters.AddWithValue("@MealID", MealID);
                comm.Parameters.AddWithValue("@qty", qty);
                comm.Parameters.AddWithValue("@districtID", districtID);
                comm.Parameters.AddWithValue("@Remark", Remark);

                resultLine = pd.ExeSqlCode(comm, dbName);

                if (state == "add" && resultLine > 0)
                {
                    joResult["message"] = "添加加班餐 " + Date + " 成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else if (state == "add" && resultLine <= 0)
                {
                    joResult["message"] = "添加加班餐 " + Date + " 失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }
                else if (state == "modify" && resultLine > 0)
                {
                    joResult["message"] = "修改加班餐 " + Date + " 成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else if (state == "modify" && resultLine <= 0)
                {
                    joResult["message"] = "修改加班餐 " + Date + " 失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }
                else if (state == "del" && resultLine > 0)
                {
                    joResult["message"] = "删除加班餐 " + Date + " 成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else if (state == "del" && resultLine <= 0)
                {
                    joResult["message"] = "删除加班餐 " + Date + " 失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }

            }
            catch (Exception ex)
            {
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }

            return joResult;
        }
        
        /// <summary>
        /// 审核/取消审核 加班餐
        /// </summary>
        /// <param name="districtID"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public JObject AuditMeal(JObject joParam)
        {
            JObject joResult = new JObject();
            try
            {
                int districtID = (int)joParam["districtId"];
                int id = (int)joParam["id"];
                bool isAudit = (bool)joParam["isAudit"];
                int resultLine = 0;
                string dbName = bi.GetDBName(districtID);
                SqlCommand scomm = new SqlCommand()
                {
                    CommandText = "UPDATE IncrementalMeal SET isAudit = @isAudit WHERE ID = @id and Type = 3"
                };

                scomm.Parameters.AddWithValue("@id", id);
                scomm.Parameters.AddWithValue("@isAudit", isAudit);
                resultLine = pd.ExeSqlCode(scomm, dbName);

                if (resultLine > 0)
                {
                    joResult["message"] = "审批成功";
                    joResult["data"] = resultLine;
                    joResult["state"] = true;
                }
                else
                {
                    joResult["message"] = "审批失败";
                    joResult["data"] = resultLine;
                    joResult["state"] = false;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                joResult["data"] = 0;
                joResult["message"] = ex.Message + "\n" + ex.StackTrace;
                joResult["state"] = false;
            }
            return joResult;
        }
    }
}
